# -*- coding: UTF-8 -*-

import socket
import threading
import json
from PyQt5.QtCore import QSettings
import pathlib
import os

# 建立一个服务端
# 

new_masg = ''
def server_meth():
    print('服务端加载完毕')
    global server
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(('localhost', 6998))  # 绑定要监听的端口
    server.listen()


def handle_sock(sock, addr, _user_message,_welcome_message, _class_message):
    all_score = []
    anser_list = [['imread','imwrite','imshow'],\
                  ['img','img.shape','np.float'],\
                  ['np.fft.fft2','np.fft.fftshift','ifftshift'],\
                  ['np.fft.fft2','f1shift','ifft2'],\
                  ['medianBlur','blur','GaussianBlur'],\
                  ['array','np.float32','convolve2d'],\
                  ['imread','convertScaleAbs','addWeighted']]

    while True:
        try:
            data = sock.recv(1024)

            if not data:
                print("connect close..")
                break

            receive_msg = data.decode("utf-8")

            if receive_msg == "client_on_line":
                sock.send(bytes('serving_online', encoding="utf8"))
                print('有用户连接')


            if receive_msg == "get_user_message":
                msg = json.dumps(_user_message)
                sock.send(msg.encode('utf-8'))

            if receive_msg == "get_class_message":
                msg = json.dumps(_class_message)
                sock.send(msg.encode('utf-8'))  # 发送一条信息 python3 只接收btye流

            if receive_msg == "get_welcome_message":
                msg = json.dumps(_welcome_message)
                sock.send(msg.encode('utf-8'))  # 发送一条信息 python3 只接收btye流

            if receive_msg == "alive":
                sock.send(bytes('serving_online', encoding="utf8"))

            if receive_msg[0:5] == "score":
                #all_score.append()
                sock.send(bytes('serving_online', encoding="utf8"))
            if receive_msg[0:5] == 'anser':
                info = json.loads(receive_msg[5:])
                print (info)
                score_info = []
                sc = 0
                for i in range(3):
                    if info[1][i+1] == anser_list[info[0]][i]:
                        sc += 33
                score_info.append(sc)  # 得分
                score_info.append(info[1][0]) #用户名

                if os.path.exists("score"):
                    os.remove("score")
                    file_name = "score"
                    pathlib.Path(file_name).touch()
                else:
                    file_name = "score"
                    pathlib.Path(file_name).touch()
                with open('score',mode= 'r+' ,encoding='utf-8') as wf:
                    wf.writelines(json.dumps(score_info, ensure_ascii=False))
                sock.send(bytes('serving_online', encoding="utf8"))

            # sock.send(data.upper())
        except ConnectionResetError:
            print('用户关闭了连接')
            break
    sock.close()


def server_start():
    with open('info', 'r', encoding='utf-8') as f:
        user_message = f.readline()
        welcome_message = f.readline()
        class_message = f.readline()
    server_meth()
    while True:
        sock, addr = server.accept()
        client_thread = threading.Thread(target=handle_sock, args=(sock, addr, user_message,welcome_message, class_message))
        client_thread.start()


